<template>
  <div class="tag-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card shadow="never">
        <el-form :model="searchForm" inline>
          <el-form-item label="标签名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入标签名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <!-- 使用频率筛选暂未在新API中支持 -->
          <!-- <el-form-item label="使用频率">
            <el-select
              v-model="searchForm.usageLevel"
              placeholder="选择频率"
              clearable
              style="width: 120px"
            >
              <el-option label="未使用" :value="0" />
              <el-option label="低频" :value="1" />
              <el-option label="中频" :value="2" />
              <el-option label="高频" :value="3" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="使用次数">
            <el-input-number
              v-model="searchForm.minUseCount"
              placeholder="最小"
              :min="0"
              style="width: 140px"
            />
            <span style="margin: 0 8px">-</span>
            <el-input-number
              v-model="searchForm.maxUseCount"
              placeholder="最大"
              :min="0"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 350px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作区域 -->
    <div class="operation-container">
      <el-card shadow="never">
        <div class="operation-bar">
          <div class="left-operations">
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              新建标签
            </el-button>
            <el-button
              type="success"
              :disabled="!hasSelection"
              @click="handleBatchOperation('ENABLE')"
            >
              <el-icon><Select /></el-icon>
              批量启用
            </el-button>
            <el-button
              type="warning"
              :disabled="!hasSelection"
              @click="handleBatchOperation('DISABLE')"
            >
              <el-icon><Close /></el-icon>
              批量禁用
            </el-button>
            <el-button
              type="danger"
              :disabled="!hasSelection"
              @click="handleBatchOperation('DELETE')"
            >
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
            <el-dropdown @command="handleDropdownCommand">
              <el-button>
                更多操作
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="cleanup"
                    >清理未使用标签</el-dropdown-item
                  >
                  <el-dropdown-item command="sync"
                    >同步使用次数</el-dropdown-item
                  >
                  <el-dropdown-item command="export">导出标签</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="right-operations">
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="showStatistics = true">
              <el-icon><DataAnalysis /></el-icon>
              统计信息
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-card shadow="never">
        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" sortable="custom" />
          <el-table-column prop="name" label="标签名称" min-width="150">
            <template #default="{ row }">
              <div class="tag-display">
                <el-tag
                  :color="row.color"
                  :style="{ color: getTextColor(row.color) }"
                  class="tag-item"
                >
                  {{ row.name }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="color" label="颜色" width="100" align="center">
            <template #default="{ row }">
              <div class="color-display">
                <div
                  class="color-block"
                  :style="{ backgroundColor: row.color }"
                  @click="handleColorEdit(row)"
                />
                <span class="color-text">{{ row.color }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="useCount"
            label="使用次数"
            width="120"
            sortable="custom"
            align="center"
          >
            <template #default="{ row }">
              <div class="use-count">
                <span class="count">{{ formatUseCount(row.useCount) }}</span>
                <el-tag
                  :type="getUsageLevelTagType(row.usageLevel) as any"
                  size="small"
                  class="level-tag"
                >
                  {{ row.usageLevelText || getUsageLevelText(row.usageLevel) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="100"
            align="center"
          >
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status) as any">
                {{ row.statusText || getTagStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="articleCount"
            label="文章数量"
            width="120"
            align="center"
          >
            <template #default="{ row }">
              <div v-if="row.articleCount !== undefined" class="article-count">
                <span class="total">{{ row.articleCount }}</span>
                <div
                  v-if="row.publishedArticleCount !== undefined"
                  class="detail"
                >
                  <span class="published"
                    >发布: {{ row.publishedArticleCount }}</span
                  >
                  <span class="draft">草稿: {{ row.draftArticleCount }}</span>
                </div>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="lastUsedTime" label="最后使用" width="180">
            <template #default="{ row }">
              <span v-if="row.lastUsedTime">{{ row.lastUsedTime }}</span>
              <span v-else class="no-data">从未使用</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            sortable="custom"
          />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button
                v-if="row.status === 0"
                type="success"
                size="small"
                @click="handleEnable(row)"
              >
                启用
              </el-button>
              <el-button
                v-if="row.status === 1"
                type="warning"
                size="small"
                @click="handleDisable(row)"
              >
                禁用
              </el-button>
              <el-dropdown
                @command="command => handleRowDropdown(command, row)"
              >
                <el-button size="small">
                  更多
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="reset"
                      >重置次数</el-dropdown-item
                    >
                    <el-dropdown-item command="similar"
                      >相似标签</el-dropdown-item
                    >
                    <el-dropdown-item command="delete" divided
                      >删除</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 标签编辑对话框 -->
    <TagEditDialog
      v-model:visible="showEditDialog"
      :tag="currentTag"
      :is-edit="isEdit"
      @success="handleEditSuccess"
    />

    <!-- 批量操作确认对话框 -->
    <BatchOperationDialog
      v-model:visible="showBatchDialog"
      :operation-type="batchOperationType"
      :selected-tags="selectedTags"
      @confirm="handleBatchConfirm"
    />

    <!-- 统计信息对话框 -->
    <TagStatisticsDialog v-model:visible="showStatistics" />

    <!-- 颜色选择器对话框 -->
    <ColorPickerDialog
      v-model:visible="showColorPicker"
      :tag="currentTag"
      @confirm="handleColorConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Select,
  Close,
  Delete,
  DataAnalysis,
  ArrowDown
} from "@element-plus/icons-vue";
import {
  getTagListApi,
  deleteTagApi,
  batchOperateTagsApi,
  getTagStatisticsApi,
  checkTagNameApi,
  type TagInfo,
  type TagListQuery,
  type BatchOperationParams,
  formatTagColor,
  getUsageLevelText,
  getTagStatusText,
  formatUseCount
} from "@/api/article-tag";
import TagEditDialog from "./components/TagEditDialog.vue";
import BatchOperationDialog from "./components/BatchOperationDialog.vue";
import TagStatisticsDialog from "./components/TagStatisticsDialog.vue";
import ColorPickerDialog from "./components/ColorPickerDialog.vue";

// 响应式数据
const loading = ref(false);
const tableData = ref<TagInfo[]>([]);
const selectedTags = ref<TagInfo[]>([]);
const showEditDialog = ref(false);
const showBatchDialog = ref(false);
const showStatistics = ref(false);
const showColorPicker = ref(false);
const isEdit = ref(false);
const currentTag = ref<TagInfo | null>(null);
const batchOperationType = ref<string>("ENABLE");

// 搜索表单类型
interface SearchForm {
  name: string;
  status?: number;
  minUseCount?: number;
  maxUseCount?: number;
  keyword: string;
  onlyEnabled?: boolean;
  onlyUsed?: boolean;
  sortField: string;
  sortOrder: "asc" | "desc";
}

// 搜索表单（不包含分页参数）
const searchForm = reactive<SearchForm>({
  name: "",
  status: undefined,
  minUseCount: undefined,
  maxUseCount: undefined,
  keyword: "",
  onlyEnabled: undefined,
  onlyUsed: undefined,
  sortField: "sort_order",
  sortOrder: "asc"
});

const dateRange = ref<[string, string] | null>(null);

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 计算属性
const hasSelection = computed(() => selectedTags.value.length > 0);

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    const params: TagListQuery = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    };

    // 调试信息：检查分页参数
    console.log("标签列表查询参数:", params);
    console.log("当前分页状态:", {
      current: pagination.current,
      size: pagination.size,
      total: pagination.total
    });

    // 新API中暂不支持时间范围查询
    // if (dateRange.value) {
    //   params.startTime = dateRange.value[0];
    //   params.endTime = dateRange.value[1];
    // }

    const data = await getTagListApi(params);

    if (data && data.code === 200) {
      tableData.value = data.data.records;
      pagination.total = data.data.total;
    } else {
      ElMessage.error(data?.message || "获取标签列表失败");
    }
  } catch (error) {
    console.error("获取标签列表失败:", error);
    ElMessage.error("获取标签列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    status: undefined,
    usageLevel: undefined,
    minUseCount: undefined,
    maxUseCount: undefined,
    includeUsageStats: true
  });
  dateRange.value = null;
  pagination.current = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleCreate = () => {
  currentTag.value = null;
  isEdit.value = false;
  showEditDialog.value = true;
};

const handleEdit = (tag: TagInfo) => {
  currentTag.value = tag;
  isEdit.value = true;
  showEditDialog.value = true;
};

const handleEditSuccess = () => {
  loadData();
};

const handleSelectionChange = (selection: TagInfo[]) => {
  selectedTags.value = selection;
};

const handleSortChange = ({ prop, order }: any) => {
  if (prop && order) {
    searchForm.sortField = prop;
    searchForm.sortOrder = order === "ascending" ? "asc" : "desc";
    loadData();
  }
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadData();
};

const handleCurrentChange = (current: number) => {
  console.log("分页切换:", current, "->", current);
  pagination.current = current;
  console.log("更新后的分页状态:", pagination.current);
  loadData();
};

const getTextColor = (backgroundColor: string): string => {
  // 简单的颜色对比度计算，返回合适的文字颜色
  const hex = backgroundColor.replace("#", "");
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness > 128 ? "#000000" : "#ffffff";
};

const getUsageLevelTagType = (level: number | undefined): string => {
  // 确保level是有效的数字
  if (level === undefined || level === null) {
    return "info";
  }
  const typeMap: Record<number, string> = {
    0: "info",
    1: "success",
    2: "warning",
    3: "danger"
  };
  return typeMap[level] || "info";
};

const getStatusTagType = (status: number | undefined): string => {
  // 确保status是有效的数字
  if (status === undefined || status === null) {
    return "info";
  }
  return status === 1 ? "success" : "danger";
};

const handleEnable = async (tag: TagInfo) => {
  try {
    await ElMessageBox.confirm(`确定要启用标签"${tag.name}"吗？`, "确认操作", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const data = await batchOperateTagsApi({
      tagIds: [tag.id],
      operation: "enable"
    });

    if (data && data.code === 200) {
      ElMessage.success("标签启用成功");
      loadData();
    } else {
      ElMessage.error(data?.message || "标签启用失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("启用标签失败:", error);
      ElMessage.error("启用标签失败");
    }
  }
};

const handleDisable = async (tag: TagInfo) => {
  try {
    await ElMessageBox.confirm(`确定要禁用标签"${tag.name}"吗？`, "确认操作", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const data = await batchOperateTagsApi({
      tagIds: [tag.id],
      operation: "disable"
    });

    if (data && data.code === 200) {
      ElMessage.success("标签禁用成功");
      loadData();
    } else {
      ElMessage.error(data?.message || "标签禁用失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("禁用标签失败:", error);
      ElMessage.error("禁用标签失败");
    }
  }
};

const handleColorEdit = (tag: TagInfo) => {
  currentTag.value = tag;
  showColorPicker.value = true;
};

const handleColorConfirm = () => {
  loadData();
};

const handleBatchOperation = (operationType: string) => {
  batchOperationType.value = operationType;
  showBatchDialog.value = true;
};

const handleBatchConfirm = async (params: any) => {
  try {
    const data = await batchOperateTagsApi(params);

    if (data && data.code === 200) {
      const result = data.data;
      if (result) {
        ElMessage.success(
          `${result.details} (成功: ${result.successCount}, 失败: ${result.failCount})`
        );
      } else {
        ElMessage.success("批量操作成功");
      }
      selectedTags.value = [];
      loadData();
    } else {
      ElMessage.error(data?.message || "批量操作失败");
    }
  } catch (error) {
    console.error("批量操作失败:", error);
    ElMessage.error("批量操作失败");
  }
};

const handleDropdownCommand = async (command: string) => {
  switch (command) {
    case "cleanup":
      await handleCleanup();
      break;
    case "sync":
      await handleSync();
      break;
    case "export":
      handleExport();
      break;
  }
};

const handleRowDropdown = async (command: string, tag: TagInfo) => {
  switch (command) {
    case "reset":
      await handleResetCount(tag);
      break;
    case "similar":
      handleShowSimilar(tag);
      break;
    case "delete":
      await handleDelete(tag);
      break;
  }
};

const handleDelete = async (tag: TagInfo) => {
  try {
    let forceDelete = false;

    // 如果标签被使用，询问是否强制删除
    if (tag.useCount > 0) {
      const result = await ElMessageBox.confirm(
        `标签"${tag.name}"已被 ${tag.useCount} 篇文章使用，删除后相关文章的标签信息将被更新。确定要强制删除吗？`,
        "确认强制删除",
        {
          confirmButtonText: "强制删除",
          cancelButtonText: "取消",
          type: "error",
          distinguishCancelAndClose: true
        }
      );
      forceDelete = true;
    } else {
      await ElMessageBox.confirm(
        `确定要删除标签"${tag.name}"吗？删除后不可恢复！`,
        "确认删除",
        {
          confirmButtonText: "确定删除",
          cancelButtonText: "取消",
          type: "warning"
        }
      );
    }

    const data = await deleteTagApi(tag.id);

    if (data && data.code === 200) {
      ElMessage.success("标签删除成功");
      loadData();
    } else {
      ElMessage.error(data?.message || "标签删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除标签失败:", error);
      ElMessage.error("删除标签失败");
    }
  }
};

const handleResetCount = async (tag: TagInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置标签"${tag.name}"的使用次数吗？`,
      "确认重置",
      {
        confirmButtonText: "确定重置",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const data = await batchOperateTagsApi({
      tagIds: [tag.id],
      operation: "resetUseCount"
    });

    if (data && data.code === 200) {
      ElMessage.success("使用次数重置成功");
      loadData();
    } else {
      ElMessage.error(data?.message || "重置失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("重置使用次数失败:", error);
      ElMessage.error("重置使用次数失败");
    }
  }
};

const handleShowSimilar = (tag: TagInfo) => {
  ElMessage.info(`查看与"${tag.name}"相似的标签功能开发中...`);
};

const handleCleanup = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清理30天前创建且未使用的标签吗？此操作不可恢复！",
      "确认清理",
      {
        confirmButtonText: "确定清理",
        cancelButtonText: "取消",
        type: "error"
      }
    );

    // 清理未使用标签功能暂未在新API中实现
    ElMessage.warning("清理未使用标签功能暂未在新API中实现");
  } catch (error) {
    if (error !== "cancel") {
      console.error("清理失败:", error);
      ElMessage.error("清理失败");
    }
  }
};

const handleSync = async () => {
  try {
    // 同步标签次数功能暂未在新API中实现
    ElMessage.warning("同步标签次数功能暂未在新API中实现");
  } catch (error) {
    console.error("同步失败:", error);
    ElMessage.error("同步失败");
  }
};

const handleExport = () => {
  ElMessage.info("导出功能开发中...");
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.tag-management {
  padding: 20px;
}

.search-container,
.operation-container,
.table-container {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.left-operations,
.right-operations {
  display: flex;
  gap: 8px;
}

.tag-display {
  display: flex;
  align-items: center;
}

.tag-item {
  font-weight: 500;
  border: none;
}

.color-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.color-block {
  width: 20px;
  height: 20px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.color-text {
  font-size: 12px;
  color: #909399;
}

.use-count {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.count {
  font-weight: 600;
  color: #303133;
}

.level-tag {
  margin: 0;
}

.article-count {
  text-align: center;
}

.article-count .total {
  font-weight: 600;
  color: #303133;
}

.article-count .detail {
  margin-top: 2px;
  font-size: 12px;
  color: #909399;
}

.article-count .detail span {
  display: block;
}

.no-data {
  font-style: italic;
  color: #c0c4cc;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
